/**
 *
 * 2007-11-2 上午10:47:10
 * @author xuhuan
 */

package edu.ccut.saturn.studio.logic.model.xml.loader;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnStartNode;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnSwichNode;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnSwichVO;

public class SwichNodeLoader extends NodeLoader {

	protected SaturnStartNode createStartNode() {
		return new SaturnStartNode();
	}

	public List<Shape> loadNodes(Element root) {
		NodeList startNodes = root
				.getElementsByTagName(SaturnSwichNode.SWICH_NODE_NAME);

		List<Shape> shapes = new ArrayList<Shape>(startNodes.getLength());

		for (int i = 0; i < startNodes.getLength(); ++i) {
			SaturnSwichNode saturnSwichNode = new SaturnSwichNode();
			Node swichNode = startNodes.item(i);
			saturnSwichNode.setNode(swichNode);
			String shapeId = super.getNodeAttributeValue(swichNode,
					Shape.KEY_ATTRIBUTE_SHAPE_ID);
			String nextId = super.getNodeAttributeValue(swichNode,
					Shape.KEY_ATTRIBUTE_SHAPE_NEXT_ID);
			String name = super.getNodeElementValue(swichNode,
					Shape.KEY_PARAMETER_ATTRIBUTE_NAME);

			String description = super.getNodeElementValue(swichNode,
					Shape.KEY_PARAMETER_NODE_DESCRIPTION);
			Point location = super.getLocation(swichNode);
			Dimension size = new Dimension(50, 70);
			
			saturnSwichNode.setSaturnSwichConnections(getChilde(swichNode));
			saturnSwichNode.setId(shapeId);
			saturnSwichNode.setLocation(location);
			saturnSwichNode.setName(name);
			saturnSwichNode.setNextId(nextId);
			saturnSwichNode.setDescription(description);
			saturnSwichNode.setSize(size);

			shapes.add(saturnSwichNode);
		}

		return shapes;
	}
	private List<SaturnSwichVO> getChilde(Node node){
		NodeList nodeList = node.getChildNodes();
		List<SaturnSwichVO> list = new ArrayList<SaturnSwichVO>();
		
		for(int i = 0 ;i<nodeList.getLength();i++){
			Node ifNode = nodeList.item(i);
			if(ifNode.getNodeName().equals("if")){
				String isDefault = super.getNodeAttributeValue(ifNode, "isDefault");
				String then = super.getNodeAttributeValue(ifNode, "then");
				String key = super.getNodeElementValue(ifNode, "expr");
				SaturnSwichVO saturn = new SaturnSwichVO();
				saturn.setConnection(then);
				saturn.setIsDefault(isDefault);
				saturn.setKey(key);
				list.add(saturn);
			}
		}
		return list;
	}
}
